package com.example.nio.network.reactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author panghu
 * @version 1.0.0
 * @createTime 2023年08月07日 20:43:00
 * @Description
 */
public class Handler implements Runnable {

    private static final ExecutorService POOL = Executors.newFixedThreadPool(10);

    private final SocketChannel socketChannel;

    public Handler(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        try {
            ByteBuffer buffer = ByteBuffer.allocate(128);
            socketChannel.read(buffer);
            // 记得翻转位移pos
            buffer.flip();
            POOL.submit(() -> {
                try {
                    // 服务端在接受到客户端传入的数据之后   做事情时间可能很长  -- 直接开线程池处理
                    System.out.println("接收到客户端数据：" + new String(buffer.array(), 0, buffer.remaining()));
                    //直接向通道中写入数据就行
                    Thread.sleep(10000);
                    socketChannel.write(ByteBuffer.wrap("已收到！".getBytes()));
                } catch (Exception e) {
                   e.printStackTrace();
                }
            });

        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}
